package cn.lg.soar.database.base.service;

import cn.lg.soar.database.base.entity.IBaseEntity;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.cache.CacheManager;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author luguoxiang
 * @param <T>
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public interface IBaseService<T extends IBaseEntity> extends IService<T> {

    /**
     * 获取第一条数据
     * @param queryWrapper
     * @return
     */
    default T getFirst(Wrapper<T> queryWrapper) {
        Page<T> page = page(new Page<T>(1, 1, false), queryWrapper);
        List<T> records = page.getRecords();
        if (records.isEmpty()) {
            return null;
        }
        return records.get(0);
    }

    /**
     * 数据是否存在
     * @param wrapper
     * @return
     */
    boolean exist(QueryWrapper<T> wrapper);

    /**
     * 数据是否存在
     * @param wrapper
     * @return
     */
    boolean exist(LambdaQueryWrapper<T> wrapper);

    @Override
    default List<T> listByIds(Collection<? extends Serializable> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return Collections.emptyList();
        }
        return this.getBaseMapper().selectBatchIds(idList);
    }

    /**
     * 基于缓存查询
     * @param idList
     * @return
     */
    List<T> listByIds(Collection<? extends Serializable> idList, String cacheName, CacheManager cacheManager);

    /**
     * 基于缓存查询
     * @param idList
     * @param cacheName
     * @return
     */
    List<T> listByIds(Collection<? extends Serializable> idList, String cacheName);

    /**
     * 获取列表
     * @param wrapper 条件
     * @param limit 获取的条数
     * @return
     */
    default List<T> list(Wrapper<T> wrapper, Integer limit) {
        if (limit == null) {
            return list(wrapper);
        }
        Page<T> page = new Page<>(0, limit, false);
        return page(page, wrapper).getRecords();
    }

    /**
     * 获取列表
     * @param wrapper 条件
     * @param limit 获取的条数
     * @return
     */
    default List<Map<String, Object>> listMaps(Wrapper<T> wrapper, Integer limit) {
        if (limit == null) {
            return listMaps(wrapper);
        }
        Page<Map<String, Object>> page = new Page<>(0, limit, false);
        return pageMaps(page, wrapper).getRecords();
    }

}
